<template>
  <div class="app-container">
    <!-- <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
      @reset-click="resetClick">    </page-search> -->
    <PageContent ref="contentRef" :gridOptions="gridOptions" :content-config="contentConfig" @addClick="addFn"
      @edit-click="handleEditClick" @export-click="handleExportClick" >
      <template #type="scope">
        {{ t(`label.${scope.row.type}`) }}
      </template>
      <template #status="scope">
        <el-tag type="success" v-if="scope.row.status === 'active'">{{ t(`status.48`) }}</el-tag>
        <el-tag type="danger" v-else-if="scope.row.status === 'inactive'">{{ t(`status.49`) }}</el-tag>
      </template>
      <template #visible="scope">
        <el-tag type="success" v-if="scope.row.visible">{{ t(`status.1`) }}</el-tag>
        <el-tag type="danger" v-else>{{ t(`status.2`) }}</el-tag>
      </template>
      <template #started_at="scope">
        {{ formatDateTime(scope.row.started_at) }}
      </template>
      <template #ended_at="scope">
        {{ formatDateTime(scope.row.ended_at) }}
      </template>
    </PageContent>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #type="scope">
        <el-select v-model="param[scope.prop]" @change="(val) => updateModalFormData('add', 'type')">
          <template v-for="option in typeList" :key="option.value">
            <el-option :label="t('label.' + option.label)" :value="option.value" />
          </template>
        </el-select>
      </template>
      <template v-if="!!param.type" #metadata="scope">
        <div class="w-full" v-for="(item, index) in param.metadata.rules" :key="index">
          <el-row :gutter="15" class="w-full mb-2">
            <el-col v-if="item.hasOwnProperty('vip_level')" :span="6">
              <el-text>{{ t('label.vip_level') }}</el-text>
              <el-select v-model="item.vip_level" @change="() => updateModalFormData('add', 'metadata')">
                <el-option v-for="option in vipLevelList" :key="option.value" :label="option.label"
                  :value="option.value" />
              </el-select>
            </el-col>
            <el-col v-if="item.hasOwnProperty('valid_bet_amount')" :span="7">
              <el-text>{{ t('label.valid_bet_amount') }}</el-text>
              <el-input v-model.number="item.valid_bet_amount" :placeholder="t('hint.145')"
              @change="() => updateModalFormData('add', 'metadata')" />
            </el-col>
            <el-col v-if="item.hasOwnProperty('rebate_rate')" :span="7">
              <el-text>{{ t('label.rebate_rate') }}</el-text>
              <el-input v-model="item.rebate_rate" :placeholder="t('hint.145')" @change="() => updateModalFormData('add', 'metadata')" />
            </el-col>
            <el-col v-if="item.hasOwnProperty('bonus')" :span="14">
              <el-text>{{ t('label.bonus') }}</el-text>
              <el-input v-model.number="item.bonus" :placeholder="t('hint.145')" @change="() => updateModalFormData('add', 'metadata')" />
            </el-col>
            <el-col :span="4" class="mt-8">
              <el-button v-if="index === 0" type="primary" class="block w-full" @click="addMeta">{{ t('btn.17')
                }}</el-button>
              <el-button v-if="param.metadata.rules.length > 1 && index !== 0" type="danger" class="block w-full"
                @click="removeMeta(index)">{{ t('btn.4') }}</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
      <template #image="scope">
        <div class="flex w-full gap-20px items-center">
          <single-upload v-model="param[scope.prop]" returnType="path" :form-data="param" @change="(val) => updateModalFormData('add','image')" />
          <el-input v-model="param[scope.prop]" :autosize="{ minRows: 6, maxRows: 6 }" type="textarea"
            class="w-1px flex-1" :placeholder="$t('hint.115')"
            @input="(val) => updateModalFormData('add','image')" 
           />
        </div>
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal ref="editModalRef" :modal-config="editModalConfig" @submit-click="handleSubmitClick">
      <template #type="scope">
        <el-select v-model="param[scope.prop]" @change="(val) => updateModalFormData('edit', 'type')">
          <template v-for="option in typeList" :key="option.value">
            <el-option :label="t('label.' + option.label)" :value="option.value" />
          </template>
        </el-select>
      </template>
      <template v-if="!!param.type" #metadata="scope">
        <div class="w-full" v-for="(item, index) in param.metadata.rules" :key="index">
          <el-row :gutter="15" class="w-full mb-2">
            <el-col v-if="item.hasOwnProperty('vip_level')" :span="6">
              <el-text>{{ t('label.vip_level') }}</el-text>
              <el-select v-model="item.vip_level" @change="() => updateModalFormData('edit', 'metadata')">
                <el-option v-for="option in vipLevelList" :key="option.value" :label="option.label"
                  :value="option.value" />
              </el-select>
            </el-col>
            <el-col v-if="item.hasOwnProperty('valid_bet_amount')" :span="7">
              <el-text>{{ t('label.valid_bet_amount') }}</el-text>
              <el-input v-model.number="item.valid_bet_amount" :placeholder="t('hint.145')"
              @change="() => updateModalFormData('edit', 'metadata')" />
            </el-col>
            <el-col v-if="item.hasOwnProperty('rebate_rate')" :span="7">
              <el-text>{{ t('label.rebate_rate') }}</el-text>
              <el-input v-model="item.rebate_rate" :placeholder="t('hint.145')" @change="() => updateModalFormData('edit', 'metadata')" />
            </el-col>
            <el-col v-if="item.hasOwnProperty('bonus')" :span="14">
              <el-text>{{ t('label.bonus') }}</el-text>
              <el-input v-model.number="item.bonus" :placeholder="t('hint.145')" @change="() => updateModalFormData('edit', 'metadata')" />
            </el-col>
            <el-col :span="4" class="mt-8">
              <el-button v-if="index === 0" type="primary" class="block w-full" @click="addMeta">{{ t('btn.17')
                }}</el-button>
              <el-button v-if="param.metadata.rules.length > 1 && index !== 0" type="danger" class="block w-full"
                @click="removeMeta(index)">{{ t('btn.4') }}</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
      <template #image="scope">
        <div class="flex w-full gap-20px items-center">
          <single-upload v-model="param[scope.prop]" returnType="path" :form-data="param" @change="(val) => updateModalFormData('edit','image')" />
          <el-input v-model="param[scope.prop]" :autosize="{ minRows: 6, maxRows: 6 }" type="textarea"
            class="w-1px flex-1" :placeholder="$t('hint.115')"
            @input="(val) => updateModalFormData('edit','image')" 
           />
        </div>
      </template>
    </page-modal>
  </div>
</template>

<script setup>
import contentConfig from "./config/content";
import addModalConfig from "./config/add";
import editModalConfig from "./config/edit";
import usePage from "@/hooks/usePage";
import API from '@/api/client/levels.js'
import { tableHeightAutoAdjust, formatDateTime } from '@/utils/common'
import { onMounted } from "vue";

const { t } = useI18n();

defineOptions({
  name: "operationsEvents",
  inheritAttrs: false,
});
const gridOptions = reactive({})
const { contentRef, addModalRef, editModalRef,
  handleAddClick,
  handleSubmitClick, handleExportClick, } = usePage();

// 初始化数据
const param = reactive({
  type: "",
  status: "",
  metadata: {
    rules: [
      {
        vip_level: null,
        valid_bet_amount: null,
        rebate_rate: null
      },
    ]
  },
  image: "",
  text: ""
})

const typeList = ref([
  {
    label: "rebate",
    value: "rebate",
  },
  {
    label: 'check_in',
    value: "check_in",
  },
])

const vipLevelList = ref([])

const isEdit = ref(null)
watch(() => [param.type, isEdit.value], ([newType, newIsEdit]) => {
  if (!newIsEdit) {
    console.log('监听===>', newType)
    if (newType === 'check_in') {
      param.metadata.rules = [
        {
          vip_level: null,
          bonus: null,
        },
      ]
    } else {
      param.metadata.rules = [
        {
          vip_level: null,
          valid_bet_amount: null,
          rebate_rate: null
        },
      ]
    }
  }
}, {
  immediate: true
})

// 更新metadata方法
const updateModalFormData = (type,key) => {
  if (type === 'add') {
    addModalRef.value?.updateFormData(key,param[key]);
  } else if (type === 'edit') {
    editModalRef.value?.updateFormData(key, param[key]);
  }
}


// const searchParam = ref({})
// const setSearchParam = () => {
//   searchRef.value.setParams(searchParam.value)
// }
// const resetClick = () => {
//   for (let i in searchParam.value) {
//     searchParam.value[i] = ''
//   }
//   handleResetClick()
// }

const handleEditClick = (row) => {
  console.log('row编辑===>', row)
  isEdit.value = true

  // 重置param对象以避免之前编辑的数据持续存在
  param.type = row.type || ""
  param.status = row.status || ""

  // 正确处理metadata
  if (!row.metadata || !row.metadata.rules || row.metadata.rules.length === 0) {
    // 根据类型初始化默认metadata结构
    if (row.type === 'check_in') {
      param.metadata = {
        rules: [
          {
            vip_level: null,
            bonus: null,
          },
        ]
      }
    } else {
      param.metadata = {
        rules: [
          {
            vip_level: null,
            valid_bet_amount: null,
            rebate_rate: null
          },
        ]
      }
    }
  } else {
    // 深拷贝metadata以避免引用问题
    param.metadata = JSON.parse(JSON.stringify(row.metadata))
  }

  // 将row的其他属性复制到param
  for (let i in row) {
    if (i !== 'metadata' && i !== 'type' && i !== 'status') {
      param[i] = row[i]
    }
  }

  console.log('param===>', param)
  // 只将param传递给setModalVisible以避免冲突
  editModalRef.value?.setModalVisible(param);
}

const addFn = () => {
  isEdit.value = false
  param.image = ""
  param.image_url = ""
  param.content = ""
  param.type = ""
  handleAddClick()
}

const addMeta = () => {
  if (param.type === 'check_in') {
    param.metadata.rules.push({
      vip_level: null,
      bonus: null,
    });
  } else {
    param.metadata.rules.push({
      vip_level: null,
      valid_bet_amount: null,
      rebate_rate: null
    });
  }

};
const removeMeta = (index) => {
  param.metadata.rules.splice(index, 1);
};

function getVipLevelList() {
  API.getList().then((res) => {
    vipLevelList.value = res.data.map((item) => {
      return {
        label: item.name,
        value: item.level,
      }
    })
  });
}

onMounted(() => {
  // 确保在组件挂载后立即设置高度
  tableHeightAutoAdjust(gridOptions);
  // 获取会员等级
  getVipLevelList();
});
</script>

<style></style>
